﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using SystemX;
namespace SystemX.Web.Infrastructure
{
	[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
	public class FlexigridFieldAttribute : Attribute
	{
		public FlexigridFieldAttribute():this(0){ }
		public FlexigridFieldAttribute(int order) {
			DisplayOrder = order;
		}
		public int DisplayOrder { get; set; }

		public static List<PropertyInfo> GetFlexigridFields(Type t, bool includeBaseProperties)
		{
			var retVal = new List<PropertyInfo>();
			if (includeBaseProperties)
			{
				retVal = t.GetProperties(SystemX.ObjectX.DefaultBindingFlags).ToList();
			}
			else
			{
                retVal = t.GetProperties(SystemX.ObjectX.ExcludeBaseBindingFlags).ToList();
			}

			retVal = retVal
			.Where(x =>
			{
				return x.IsDefined(typeof(FlexigridFieldAttribute), false);
			}).ToList();
			return retVal;
		}//endof GetFlexigridFields
		public static Dictionary<string,object> GetFlexigridFields<T>(T obj, bool includeBaseProperties) {
			var items = GetFlexigridFields(typeof(T), includeBaseProperties);
			//order
			var attr0=default(FlexigridFieldAttribute);
			var attr1 = default(FlexigridFieldAttribute);
			items.Sort((x,y) => {
				attr0 = x.GetCustomAttributes(typeof(FlexigridFieldAttribute), false)[0] as FlexigridFieldAttribute;
				attr1 = y.GetCustomAttributes(typeof(FlexigridFieldAttribute), false)[0] as FlexigridFieldAttribute;
				return attr0.DisplayOrder.CompareTo(attr1.DisplayOrder);
			});

			var retVal = new Dictionary<string, object>();

			items.ForEach(x => {
				retVal.Add(x.Name,obj.GetPropertyValue(x.Name));
			});
			return retVal;
		}//endof GetFlexigridFields<T>

		public static object[] GetFlexigridFieldValues<T>(T obj, bool includeBaseProperties) {
			var dics = GetFlexigridFields<T>(obj, includeBaseProperties);
			return dics.Values.ToArray<object>();
		}
	}
}
